#! /bin/bash

###
### getGeneBed 可从bed文件中筛选出需要的行
###
### Usage:
###   ./getGeneBed.sh [-abdcsio] [--help]
###
### Options:
###   -a    inbed, 区间开头, default 1
###   -b    outbed, 区间结尾, default 1
###   -d    minOverlap, 最少的区间重叠碱基数, default 1
###   -c    chr_num, 染色体号, default 1
###   -s    strand, - 或 + 链, default -
###   -i    input, 输入的文件
###   -o    output, 输出的文件
###   -h    --help, 显示帮助信息
###
### Example:
###   $ ./getGeneBed.sh -a 20034100 \
###                     -b 20147100 \
###                     -d 1 \
###                     -c 3 \
###                     -s "-" \
###                     -i "chr.bed" \
###                     -o "geneX.bed"
###

if [[ "$#" == 0 || "$1" == "-h" || "$1" == "--help" ]];then
    sed -rn 's/^### ?//;T;p;' "$0"
    exit 0
fi

inbed=1;outbed=1;minOverlap=1;chr_num=1;strand="-"

while getopts ":a:b:d:c:s:i:o:h" arg; do
    case "$arg" in
    a)
        inbed="$OPTARG"
        ;;
    b)
        outbed="$OPTARG"
        ;;
    d)
        minOverlap="$OPTARG"
        ;;
    c)
        chr_num="$OPTARG"
        ;;
    s)
        strand="$OPTARG"
        ;;
    i)
        input_file="$OPTARG"
        ;;
    o)
        result_file="$OPTARG"
        ;;
    ?)
        echo "Usage: ./getGeneBed.sh [-abdcsio] [--help]"
        exit 1
        ;;
    esac
done
shift $((OPTIND -1))

let inbed=inbed+minOverlap-1
let outbed=outbed-minOverlap+1

awk -v inbed=$inbed \
    -v outbed=$outbed \
    -v minOverlap=$minOverlap \
    -v chr_num=$chr_num \
    -v strand=$strand \
    -F '\t' '
    BEGIN{
        mark=0;
        chrpar= "([cC]hr)?"chr_num;
        printf "Runing\n";
        } \
    $1 ~ chrpar && \
    $2 <= outbed && \
    $3 >= inbed && \
    $3-$2 >= minOverlap && \
    $5 ~ strand {
        mark++;
        printf "%s\t%s\t%s\t%s\t%s\n", chr_num,$2, $3, $4, $5
        } \
    END{
        printf "# geneX: %s; total: %s\n", mark, NR 
        } \
    ' "$input_file" > "$result_file"

title=`tail -n 1 "$result_file"`
sed -i "1s/.*/$title/;\$d" "$result_file"

echo "Finish! Please cheak on" "$result_file"
